package middle

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"ylm.sl/common/constant"
	"ylm.sl/common/convention/results"
	"ylm.sl/common/enums"
	"ylm.sl/global"
	"ylm.sl/internal/model"
)

func VerifyToken() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get(global.Config.Jwt.Admin.Name)
		username := c.Request.Header.Get(enums.UserName)
		userInfoStr, err := global.Redis.HGet(c, constant.USER_LOGIN_KEY+username, token).Result()
		if err == nil {
			userInfo := &model.User{}
			if json.Unmarshal([]byte(userInfoStr), userInfo) == nil {
				// 在上下文设置载荷信息
				c.Header(enums.UserID, strconv.FormatUint(userInfo.Id, 10))
				c.Header(enums.RealName, userInfo.RealName)

				c.Set(enums.UserID, userInfo.Id)
			}

		} else {
			c.JSON(http.StatusUnauthorized, results.Result{
				Code: -1,
				Msg:  "failure",
				Data: nil,
			})
			c.Abort()
			return
		}
		c.Next()

	}
}
